// 避免命名冲突, 开启一个独立的局部作用域
; (function () {
    let position = 'absolute'

    // foods 用于存放创建的食物
    let foods = []

    function Food(options) {
        options = options || {}
        this.x = options.x || 0
        this.y = options.y || 0

        this.width = options.width || 20
        this.height = options.height || 20

        this.color = options.color || '#2ecd44'
    }

    // 渲染
    Food.prototype.render = function (map) {
        // 删除之前创建的食物
        remove()
        let foodBox = document.createElement('div')
        map.appendChild(foodBox)

        foods.push(foodBox)

        // 设置随机 x 和 y
        this.x = Tools.getRandom(0, map.offsetWidth / this.width - 1) * this.width
        this.y = Tools.getRandom(0, map.offsetHeight / this.height - 1) * this.height


        // 食物样式
        foodBox.style.position = position
        foodBox.style.left = this.x + 'px'
        foodBox.style.top = this.y + 'px'

        foodBox.style.width = this.width + 'px'
        foodBox.style.height = this.height + 'px'

        foodBox.style.backgroundColor = this.color
    }

    // 删除
    remove = () => {
        for (let i = foods.length - 1; i >= 0; i--) {
            //    删除foodBox
            foods[i].parentNode.removeChild(foods[i])
            //  删除数组中的元素
            foods.length--
        }
    }

    window.Food = Food
})()

